package com.aplana.ccsd.service;

import info.magnolia.jcr.util.PropertyUtil;
import info.magnolia.module.blossom.dialog.TabBuilder;

import java.util.ArrayList;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aplana.ccsd.constants.WebConstants;
import com.aplana.ccsd.model.Area;
import com.aplana.ccsd.model.HorizontalBlock;
import com.aplana.ccsd.model.HtmlHorizontalBlockSize;

@Service
public class HorizontalAreaServiceImpl implements HorizontalAreaService {
	
	@Autowired
	private TemplatingService templatingService;

	@Override
	public void addHorizontalAreaDialogControls(TabBuilder tabBuilder) {
		tabBuilder.addEdit("columnNumber", "Число колонок", "Число колонок по горизонтали");
		tabBuilder.addEdit("columnSpacer", "Пространство между колонками", "Пространство между колонками в px");
		tabBuilder.addEdit("containerWidth", "Ширина контейнера", "Ширина контейнера в px");
	}

	@Override
	public List<HorizontalBlock> getHorizontalBlocks(Node areaNode)
			throws PathNotFoundException, RepositoryException {
		String columnSpacer = PropertyUtil.getString(areaNode, "columnSpacer");
		String columnNumber = PropertyUtil.getString(areaNode, "columnNumber");
		String containerWidth = PropertyUtil.getString(areaNode, "containerWidth");
		
		List<Node> components = templatingService.getAreaComponents(areaNode);
		List<HorizontalBlock> horItems = new ArrayList<HorizontalBlock>();
		
		int colSpacer = 0;
		if (!org.apache.commons.lang.StringUtils.isBlank(columnSpacer)) {
			colSpacer = Integer.decode(columnSpacer);
		}
		
		int colNum = 0;
		if (org.apache.commons.lang.StringUtils.isBlank(columnNumber)) {
			if (components.size()>6) {
				colNum = 6;
			} else {
				colNum = components.size();
			}
		} else {
			colNum = Integer.decode(columnNumber);
		}
		
		int conWidth = WebConstants.SITE_WIDTH; // по умолчанию
		if (!org.apache.commons.lang.StringUtils.isBlank(containerWidth)) {
			conWidth = Integer.decode(containerWidth);
		}
		
		HtmlHorizontalBlockSize blockSize = new HtmlHorizontalBlockSize(colNum, colSpacer, conWidth);
		int i = 0;
		for (Node item: components) {
			blockSize.calculate(i);
			
			HorizontalBlock bl = new HorizontalBlock(blockSize.getWidth(), blockSize.getMarginRight(), item);
			horItems.add(bl);
			i++;
		}
		return horItems;
	}

	@Override
	public Area getHorizontalArea(Node horizontalArea)
			throws PathNotFoundException, RepositoryException {
		String containerWidth = PropertyUtil.getString(horizontalArea, "containerWidth");
		Integer conWidth = null; // по умолчанию
		if (!org.apache.commons.lang.StringUtils.isBlank(containerWidth)) {
			conWidth = Integer.decode(containerWidth);
		}
		return new Area(conWidth);
	}

}